package com.jyl.dptask;

/**
 * 最大子数组和
 *
 * @ClassName P53
 * @Author admin
 * @Date 2024/6/16
 */
public class P53 {


    public static void main(String[] args) {

        //期望输出：6
        int[] nums1 = {-2, 1, -3, 4, -1, 2, 1, -5, 4};

        //期望输出：1
        int[] nums2 = {1};

        //期望输出：23
        int[] nums3 = {5, 4, -1, 7, 8};

        System.out.println(maxSubArray(nums3));
        System.out.println(maxSubArray(nums2));
        System.out.println(maxSubArray(nums1));
    }

    public static int maxSubArray(int[] nums) {
        int[] dp = new int[nums.length];

        dp[0] = nums[0];

        int max = dp[0];

        for (int i = 1; i < nums.length; i++) {
            dp[i] = Math.max(dp[i - 1] + nums[i], nums[i]);
            max = Math.max(max, dp[i]);
        }
        return max;
    }

}
